﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Colorful.Database;
using Colorful.Models;
using System.Text;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Colorful.Cache.Web;
using System.Threading.Tasks;

namespace Colorful.CMS.Core.Controllers.Admin
{
    /// <summary>
    /// 网站设置
    /// </summary>
    [MyAuth(PermissionEnum.WebSetting)]
    public class WebSettingController : AdminBaseController
    {
        #region 首页
        public IActionResult Index(long mid)
        {
            using (var db = CMSDbHelper.GetDb())
            {
                var model = new WebSettingModel()
                {
                    IsAdmin = this.IsAdmin,
                    WebSetting = WebService.WebSetting,
                    ClearCacheUrl = this.GetUrl("clearcache"),
                    SaveUrl = this.GetUrl("websetting/save"),
                    EmailSetting = WebService.EmailSetting ?? new EmailSetting(),
                    EmailSaveUrl = this.GetUrl("emailsetting/save"),
                    CacheSetting = db.CacheSettings.FirstOrDefault() ?? new WebCacheSetting() { CacheTime = 30 },
                    CacheSaveUrl = this.GetUrl("cachesetting/save"),
                    RegCMSUrl = this.GetUrl("websetting/reg/cms"),
                    SendMailUrl = this.GetUrl("emailsetting/send"),
                    PageTitleShowTypes = EnumHelper.ToJsonData<PageTitleShowType>()
                };
                if (model.WebSetting.MaxFileSize == 0)
                    model.WebSetting.MaxFileSize = 30;
                if (model.WebSetting.WhiteFileExtensions == null || model.WebSetting.WhiteFileExtensions.Count == 0)
                    model.WebSetting.WhiteFileExtensions = new string[] { ".png", ".jpg", ".gif", ".flv", ".swf", ".mkv", ".rmvb", ".mpeg", ".mpg", ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid", ".rar", ".zip", ".tar", ".gz", ".7z", ".iso", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml" }.ToList();
                if (string.IsNullOrEmpty(model.WebSetting.AppKey))
                {
                    model.WebSetting.AppKey = WebService.GetUniqueId();
                    db.WebSettings.UpdateByPK(WebService.WebSetting.Id, b => b.AppKey, model.WebSetting.AppKey);
                }
                if (model.WebSetting.BindDomains == null || model.WebSetting.BindDomains.Count == 0)
                {
                    model.WebSetting.BindDomains = new List<string>();
                    model.WebSetting.BindDomains.Add(Request.Host.Value);
                }

                if (string.IsNullOrEmpty(model.EmailSetting.Url))
                    model.EmailSetting.Url = Request.GetDomainUrl();
                if (model.EmailSetting.Port == 0)
                    model.EmailSetting.Port = 25;
                return View(model);
            }
        }
        #endregion

        #region WebSetting 保存
        [Route("websetting/save")]
        public IActionResult SettingSave()
        {
            using (var db = CMSDbHelper.GetDb())
            {
                try
                {
                    var setting = db.WebSettings.FirstOrDefault();
                    if (setting == null)
                    {
                        setting = new WebSetting();
                        setting.Id = 1;
                        setting.AddDate = DateTime.Now;
                    }
                    setting.ModifyUser = this.LoginId;
                    setting.LastModify = DateTime.Now;
                    FormHelper.FillTo(setting, new DisableField("Id")
                        , new EncodeField("StatisticScript", "网站统计代码")
                        , new EncodeField("Scripts", "网站脚本")
                        , new TextField("BlockList", "IP黑名单") { Delimiter = '\n' });
                    db.WebSettings.Save(setting);
                    WebService.WebSetting = setting;
                    return this.GetResult(true);
                }
                catch (Exception ex)
                {
                    return this.GetResult(ex);
                }
            }
        }
        #endregion

        #region EmailSetting 保存
        [Route("emailsetting/save")]
        public IActionResult EmailSettingSave()
        {
            using (var db = CMSDbHelper.GetDb())
            {
                try
                {
                    var setting = db.EmailSettings.FirstOrDefault();
                    if (setting == null)
                    {
                        setting = new EmailSetting();
                        setting.Id = 1;
                    }
                    setting.ModifyUser = this.LoginId;
                    setting.LastModify = DateTime.Now;
                    FormHelper.FillTo(setting, new DisableField("Id"));
                    db.EmailSettings.Save(setting);
                    WebService.EmailSetting = setting;
                    return this.GetResult(true);
                }
                catch (Exception ex)
                {
                    return this.GetResult(ex);
                }
            }
        }
        [Route("emailsetting/send")]
        public IActionResult SendMail(string email)
        {
            try
            {
                if (string.IsNullOrEmpty(WebService.EmailSetting.SMTP))
                    return this.GetResult(false, "请先保存SMTP地址设置!");
                if (string.IsNullOrEmpty(WebService.EmailSetting.Username) || string.IsNullOrEmpty(WebService.EmailSetting.Password))
                    return this.GetResult(false, "请先保存用户名和密码设置!");
                var mailSetting = WebService.EmailSetting;
                //var mailService = new MailService(mailSetting.SMTP, mailSetting.Username, mailSetting.Password, mailSetting.Port);
                using (var mailService = new MailService(mailSetting.SMTP, mailSetting.Username, mailSetting.Password, mailSetting.Port, mailSetting.EnableSSL))
                {
                   // var mail = new Mail() { SendTo = email, Subject = "测试邮件", Body = "这是一封测试邮件！" };
                    mailService.SendMail(email, "测试邮件", "<strong>这是一封测试邮件！</strong>", mailSetting.SenderEmail, mailSetting.SenderName);
                }
                return this.GetResult(true);
            }
            catch (Exception ex)
            {
                this.WriteError(ex);
                return this.GetResult(false, $"Email发送失败：{ex.Message}");
            }
        }
        #endregion

        #region CacheSetting 保存
        [Route("cachesetting/save")]
        public IActionResult CacheSettingSave(WebCacheSetting cacheSetting)
        {
            using (var db = CMSDbHelper.GetDb())
            {
                try
                {
                    var setting = db.CacheSettings.FirstOrDefault();
                    if (setting == null)
                    {
                        setting = new WebCacheSetting();
                        setting.Id = 1;
                    }
                    CommonHelper.Copy(cacheSetting, setting, "Id");
                    //setting.EnableCache = cacheSetting.EnableCache;
                    //setting.EnableCompression = cacheSetting.EnableCompression;
                    //setting.EnableMinification = cacheSetting.EnableMinification;
                    //setting.CacheTime = cacheSetting.CacheTime;
                    //setting.CachePages = cacheSetting.CachePages;
                    //setting.IgnorePages = cacheSetting.IgnorePages;
                    //setting.MaxResponseSize = cacheSetting.MaxResponseSize;
                    if (setting.CachePages == null)
                        setting.CachePages = new List<CachePage>();
                    if (setting.CacheTime < 2)
                        setting.CacheTime = 2;
                    if (setting.IgnorePages == null)
                        setting.IgnorePages = new List<string>();
                    setting.IgnorePages = setting.IgnorePages.Where(a => !string.IsNullOrEmpty(a)).ToList();
                    setting.LastModify = DateTime.Now;
                    setting.ModifyUser = this.LoginId;
                    db.CacheSettings.Save(setting);
                    var cacheOptions = this.HttpContext.RequestServices.GetService<IOptions<CacheOptions>>();
                    cacheOptions.Value.Setting = setting;
                    return this.GetResult(true);
                }
                catch (Exception ex)
                {
                    return this.GetResult(ex);
                }
            }
        }
        #endregion

        #region 注册CMS
        [Route("websetting/reg/cms")]
        public async Task<IActionResult> RegCMS(string token, List<string> domains)
        {
            using (var db = CMSDbHelper.GetDb())
            {
                try
                {
                    if (string.IsNullOrEmpty(token))
                    {
                        return this.GetResult(false, "请输入Token！");
                    }
                    if (domains == null || domains.Count == 0)
                        return this.GetResult(false, "请输入要绑定的域名！");
                    db.WebSettings.UpdateByPK(this.WebSetting.Id, b => b.BindDomains, domains);
                    var url = $"{WebService.CMSAPIUrl}cms/reg";
                    var json = await HttpHelper.GetContent($"{url}?token={token}&appKey={WebService.WebSetting.AppKey}&domain={string.Join(',', domains)}&appSecret={WebSetting.AppSecret}");
                    //var json = await HttpHelper.Post(url, $"token={token}&appKey={WebService.WebSetting.AppKey}&domain={string.Join(',', domains)}&appSecret={WebSetting.AppSecret}");
                    var result = JsonHelper.Parse<Models.JsonResult>(json);
                    if (result.succ)
                    {
                        this.WebSetting.AppSecret = $"{result.data}";
                        db.WebSettings.UpdateByPK(this.WebSetting.Id, b => b.AppSecret, this.WebSetting.AppSecret);
                        return this.GetResult(true, this.WebSetting.AppSecret);
                    }
                    else
                    {
                        return this.GetResult(false, $"注册失败：{result.data}");
                    }
                }
                catch (Exception ex)
                {
                    return this.GetResult(ex);
                }
            }
        }
        #endregion
    }

    #region WebSettingModel
    public class WebSettingModel
    {
        public bool IsAdmin { get; set; }
        public WebSetting WebSetting { get; set; }
        public EmailSetting EmailSetting { get; set; }
        public WebCacheSetting CacheSetting { get; set; }
        public string SaveUrl { get; set; }
        public string ClearCacheUrl { get; set; }
        public string EmailSaveUrl { get; set; }
        public string CacheSaveUrl { get; set; }
        public string RegCMSUrl { get; set; }
        public string SendMailUrl { get; set; }
        public List<JsonData<int>> PageTitleShowTypes { get; set; }
    }
    #endregion
}